package com.javaforever.clocksimplejee4.controller;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jiangnantaste.domain.Image;
import org.jiangnantaste.service.ImageService;
import org.jiangnantaste.serviceimpl.ImageServiceImpl;
import org.jiangnantaste.utils.ImageUtil;

/**
 * Servlet implementation class UploadController
 */
public class UploadController extends HttpServlet {
	
    /**
	 * 
	 */
	private static final long serialVersionUID = 2970928096389857038L;


	public UploadController() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}
	

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		try {
			// 1. 创建工厂类
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 2. 创建FileUpload对象
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 3. 判断是否是上传表单
			boolean b = upload.isMultipartContent(request);
			if (!b) {
				// 不是文件上传
				request.setAttribute("message", "对不起，不是文件上传表单！");
				request.getRequestDispatcher("../jsp/pictureupload.jsp").forward(request, response);
				return;
			}
			// 是文件上传表单
			// 4. 解析request，获得FileItem项
			List<FileItem> fileitems = upload.parseRequest(request);
			// 5. 遍历集合
			for (FileItem item : fileitems) {
				// 判断是不是普通字段
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString();
					System.out.println(name + "=" + value);
				} else {
					// 文件上传字段
					// 获得文件名
					String filename = item.getName();
					System.out.println(filename);
					filename = filename.substring(filename.lastIndexOf(File.pathSeparator) + 1);

					System.out.println(filename);
					// 创建文件
					ServletContext context = getServletContext();
					String dir = context.getRealPath("WEB-INF/upload");
					File file = new File(dir, filename);
					file.createNewFile();

					// 获得流，读取数据写入文件
					InputStream in = item.getInputStream();
					byte[] imageData = ImageUtil.getImageBytes(in);
					
		        	ImageService service = new ImageServiceImpl();
		        	Image image = new Image();
		        	String [] filenametuple = filename.split("\\.");
		        	String imageName = filenametuple[0]+System.currentTimeMillis()+"."+filenametuple[1];
		        	image.setImageName(imageName);
		        	image.setPathName(imageName);
		        	image.setActive(true);
		        	image.setImageData(imageData);
		        	service.addImage(image);
		        	
					in.close();
					item.delete(); // 删除临时文件
					response.sendRedirect("../controller/listAllImagesController");
				}    
			}
		} catch (Exception e) {
			e.printStackTrace();
        	response.sendRedirect("../jsp/pictureupload.jsp");
		}
    }

}
